/***************************************************************************
 *   Copyright (C) 2004 by Nilesh Bansal                                   *
 *   nilesh@iitb.ac.in                                                     *
 *                                                                         *
 *   This program is free software; you can redistribute it and/or modify  *
 *   it under the terms of the GNU General Public License as published by  *
 *   the Free Software Foundation; either version 2 of the License, or     *
 *   (at your option) any later version.                                   *
 *                                                                         *
 *   This program is distributed in the hope that it will be useful,       *
 *   but WITHOUT ANY WARRANTY; without even the implied warranty of        *
 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *
 *   GNU General Public License for more details.                          *
 *                                                                         *
 *   You should have received a copy of the GNU General Public License     *
 *   along with this program; if not, write to the                         *
 *   Free Software Foundation, Inc.,                                       *
 *   59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.             *
 ***************************************************************************/

#include "ftpmonitor.h"

#include <QGraphicsTextItem>
#include <QTreeView>
#include <QHeaderView>
#include <QStringListModel>
#include <QTableWidget>

#include <KConfigDialog>
#include <KNotification>
#include <KGlobal>
#include <KStandardDirs>

#include <kdebug.h>
#include <Plasma/Applet>

FTPMonitor::FTPMonitor(QObject *parent, const QVariantList &args)
: Plasma::PopupApplet(parent, args), mListView( 0 )
{
	setAspectRatioMode(Plasma::IgnoreAspectRatio);
	setHasConfigurationInterface(true);
	
	QString iconPath = KGlobal::dirs()->locate("data", "plasma/plasmoids/ftpmonitor/ftpmonitor-disconnected.png");
	setPopupIcon(iconPath);
}

FTPMonitor::~FTPMonitor()
{	
}

void FTPMonitor::init()
{
	KConfigGroup cg = config();
	
	int ftpServer = cg.readEntry("chosenFtpServer", 1);
	QString whoPath = cg.readEntry("whoPath", "");
	
	bool useSudo = cg.readEntry("useSudo",false);
	bool allowPopup = cg.readEntry("allowPopup",true);
	int updateInterval = cg.readEntry("updateInterval",2);
	
	mMonitorLoop = new FTPMonitorLoop((FTPMonitorLoop::FtpServerType)ftpServer,whoPath,useSudo);

	connect(mMonitorLoop,SIGNAL(sigNewClientsConnected(int)), this,SLOT(newClientsConnected(int)));
	connect(mMonitorLoop,SIGNAL(sigClientsCountChanged(int)), this,SLOT(clientsCountChanged(int)));
	
	connect(mMonitorLoop,SIGNAL(sigAddRow(QStringList)),this,SLOT(addRow(QStringList)));
	connect(mMonitorLoop,SIGNAL(sigDelRow(int)),this,SLOT(delRow(int)));
	connect(mMonitorLoop,SIGNAL(sigChangeRow(QStringList,int)),this,SLOT(changeRow(QStringList,int)));
	
	mMonitorLoop->start(updateInterval,allowPopup);
}

QWidget *FTPMonitor::widget()
{
	if ( !mListView )
	{
		mListView = new QTreeWidget();
		
		mListView->setAttribute(Qt::WA_NoSystemBackground);
		mListView->setEditTriggers( QAbstractItemView::NoEditTriggers );
		mListView->setRootIsDecorated(false);
		mListView->setMouseTracking(true);

		mListView->setColumnCount(5);
		
		mListView->header()->setResizeMode(0,QHeaderView::ResizeToContents);
		mListView->header()->setResizeMode(1,QHeaderView::ResizeToContents);
		mListView->header()->setResizeMode(2,QHeaderView::ResizeToContents);
		mListView->header()->setResizeMode(3,QHeaderView::ResizeToContents);
		mListView->header()->setResizeMode(4,QHeaderView::Stretch);
		
		setHeaderLabels(mMonitorLoop->ftpServer());
	}
	return mListView;
}	
 
void FTPMonitor::createConfigurationInterface(KConfigDialog *parent)
{
	QWidget *widget = new QWidget(parent);
	mUiConfig.setupUi(widget);
	parent->addPage(widget, i18n("General"), icon());
	connect(parent, SIGNAL(applyClicked()), this, SLOT(configAccepted()));
	connect(parent, SIGNAL(okClicked()), this, SLOT(configAccepted()));
	
	KConfigGroup cg = config();
	FTPMonitorLoop::FtpServerType ftpServer= (FTPMonitorLoop::FtpServerType) cg.readEntry("chosenFtpServer",1);
	
	if (ftpServer == FTPMonitorLoop::proftpd)
	{
		mUiConfig.proftpdRadioButton->setChecked(true);
	}
	else if (ftpServer == FTPMonitorLoop::pureftpd)
	{
		mUiConfig.pureftpRadioButton->setChecked(true);
	}	
	else if (ftpServer == FTPMonitorLoop::vsftpd)
	{
		mUiConfig.vsftpdRadioButton->setChecked(true);
	}

	bool usePath = cg.readEntry("usePath",false);
	mUiConfig.chkBoxUsePath->setChecked(usePath);
	mUiConfig.lineEditUsePath->setEnabled(usePath);
	
	bool useSudo = cg.readEntry("useSudo",false);
	mUiConfig.chBoxUseSudo->setChecked(useSudo);
	
	bool allowPopup = cg.readEntry("allowPopup",true);
	mUiConfig.chBoxAllowPopup->setChecked(allowPopup);
	
	int  updateInterval = cg.readEntry("updateInterval",1);
	mUiConfig.spinBoxUpdateInterval->setValue(updateInterval);

}

void FTPMonitor::configAccepted()
{
	QString whoPath;
	KConfigGroup cg = config();
	FTPMonitorLoop::FtpServerType ftpServer;
	
	
	if (mUiConfig.pureftpRadioButton->isChecked())
		ftpServer=FTPMonitorLoop::pureftpd;
	else if (mUiConfig.proftpdRadioButton->isChecked())
		ftpServer=FTPMonitorLoop::proftpd;
	else if (mUiConfig.vsftpdRadioButton->isChecked())
		ftpServer=FTPMonitorLoop::vsftpd;
	cg.writeEntry("chosenFtpServer", (int)ftpServer);
	
	bool usePath = mUiConfig.chkBoxUsePath->isChecked();
	cg.writeEntry("usePath", usePath);
	
	if (usePath==true)
	{
		whoPath = mUiConfig.lineEditUsePath->text();
		cg.writeEntry("whoPath", whoPath);
	}
	
	bool useSudo = mUiConfig.chBoxUseSudo->isChecked();
	cg.writeEntry("useSudo", useSudo);
		
	bool allowPopup = mUiConfig.chBoxAllowPopup->isChecked();
	cg.writeEntry("allowPopup", allowPopup);
	
	int updateInterval = mUiConfig.spinBoxUpdateInterval->value();
	cg.writeEntry("updateInterval", updateInterval);
	
	mMonitorLoop->stop();
	setHeaderLabels(ftpServer);
	mMonitorLoop->createExecCommand(ftpServer,useSudo,whoPath);
	mMonitorLoop->start(updateInterval,allowPopup);
	
	emit configNeedsSaving();
}

//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

void FTPMonitor::clearClientsTable()
{
	mListView->clear();
}

void FTPMonitor::setHeaderLabels(FTPMonitorLoop::FtpServerType ftpServer)
{
	switch (ftpServer)
	{
		case FTPMonitorLoop::proftpd :
			mListView->setHeaderLabels(QStringList() << "PID" << "Login" << "What" << "Client" << "Location");
			break;
		case FTPMonitorLoop::pureftpd :
			//pid|acct|time|state|file|peer|local|port|current|total|%|bandwidth
			//mListView->setHeaderLabels(QStringList() << "PID" << "Login" << "State" << "Host");
			mListView->setHeaderLabels(QStringList() << "PID" << "Login" << "State" << "File" << "Host");
			break;
		case FTPMonitorLoop::vsftpd :
			//ftp      18677 18675  0 09:30 ?        00:00:00 vsftpd: 10.20.1.244/ftp: RETR /uploads/archlinux-2009.02-core-i686.iso
			//ftp      18699 18697  0 09:30 ?        00:00:00 vsftpd: 10.20.1.244/ftp: IDLE
			mListView->setHeaderLabels(QStringList() << "PID" << "Login" << "State" << "File" << "Host");
			break;
		case FTPMonitorLoop::ncftpd :
			break;
	}
}

void FTPMonitor::clientsCountChanged(int count)
{
	QString imgName;
	if (count > 0)
		imgName="ftpmonitor-connected.png";
	else
		imgName="ftpmonitor-disconnected.png";
	
	// http://mail.kde.org/pipermail/plasma-devel/2008-November/002279.html
	QString iconPath = KGlobal::dirs()->locate("data", "plasma/plasmoids/ftpmonitor/" + imgName);	
	setPopupIcon(iconPath);
}

void FTPMonitor::newClientsConnected(int count)
{
	QString popupText;
	if (count > 1)
		popupText=i18nc("Notification from ftpserver", "New clients connected");
	else
		popupText=i18nc("Notification from ftpserver", "New client connected");
	
	KNotification::event("clientconnected", popupText, QPixmap(), 0, KNotification::CloseOnTimeout, KComponentData("ftpmonitor", "ftpmonitor", KComponentData::SkipMainComponentRegistration));
}

void FTPMonitor::delRow(int row)
{
	delete mListView->takeTopLevelItem(row);
}

void FTPMonitor::addRow(QStringList row)
{
	mListView->addTopLevelItem(new QTreeWidgetItem((QTreeWidgetItem*)0,row));
}

void FTPMonitor::changeRow(QStringList newRow,int id)
{
	delRow(id);
	mListView->insertTopLevelItem(id,new QTreeWidgetItem((QTreeWidgetItem*)0,newRow));
}

#include "ftpmonitor.moc"
